import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:sjx/pages/setting/person_info_edit_page.dart';
import 'package:sjx/pages/setting/person_info_page_vm.dart';

import '../../repository/sjx_api.dart';
import '../../utils/sp_utils.dart';

class PersonInfoPage extends StatefulWidget {
  const PersonInfoPage({super.key});

  @override
  State<PersonInfoPage> createState() => _PersonInfoPageState();
}

class _PersonInfoPageState extends State<PersonInfoPage>  {

  late final viewModel = PersonInfoViewModel();

  final ImagePicker _imagePicker = ImagePicker();

  @override
  void initState() {
    super.initState();
    viewModel.showUserInfo();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
        create: (context) {
          return viewModel;
        },
        child: Consumer<PersonInfoViewModel>(builder: (context, value, child) {
          return Scaffold(
            appBar: AppBar(
              title: const Text('账户信息'),
              leading: IconButton(
                icon: const Icon(Icons.arrow_back),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ),
            backgroundColor: const Color.fromRGBO(244, 247, 250, 1),
            body: Column(
              children: [
                // 顶部信息卡片
                Container(
                  // margin: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(8),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.05),
                        blurRadius: 4,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Column(
                    children: [
                      // 头像行
                      _buildInfoItem(
                        title: '头像',
                        valueWidget: CachedNetworkImage(
                          imageUrl: value.avatarUrl,
                          width: 40.r,
                          height: 40.r,
                          placeholder: (context, url) {
                            return const Center(child: CircularProgressIndicator());
                          },
                          errorWidget: (context, url, error) {
                            return Image.asset(
                              'assets/images/header.png',
                              width: 40.r,
                              height: 40.r,
                              fit: BoxFit.cover,
                            );
                          },
                        ),
                        showArrow: true,
                        onTap: _showImagePicker,
                      ),
                      const Divider(height: 1, indent: 15),
                      // 昵称行
                      _buildInfoItem(
                        title: '昵称',
                        value: value.userName,
                        showArrow: true,
                        onTap: _editUserName,
                      ),
                      const Divider(height: 1, indent: 15),
                      // 账号行
                      _buildInfoItem(
                        title: '账号',
                        value: value.phone,
                        showArrow: false,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          );
        }),
    );

  }

  Widget _buildInfoItem({
    required String title,
    String? value,
    Widget? valueWidget,
    bool showArrow = false,
    VoidCallback? onTap,
  }) {
    return Material(
      color: Colors.white,
      child: InkWell(
        onTap: onTap,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
          child: Row(
            children: [
              // 标题
              SizedBox(
                width: 80,
                child: Text(
                  title,
                  style: const TextStyle(
                    fontSize: 15,
                    color: Color(0xFF262626),
                  ),
                ),
              ),
              const Spacer(),
              // 值或自定义组件
              if (valueWidget != null) valueWidget,
              if (value != null)
                Text(
                  value,
                  style: const TextStyle(
                    fontSize: 15,
                    color: Color(0xFF262626),
                  ),
                ),
              if (showArrow)
                const Padding(
                  padding: EdgeInsets.only(left: 8),
                  child: Icon(
                    Icons.arrow_forward_ios,
                    size: 12,
                    color: Color(0xFF8C8C8C),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  void _showImagePicker() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: const Icon(Icons.camera_alt),
                title: const Text('拍照'),
                onTap: () {
                  Navigator.pop(context);
                  _pickImage(ImageSource.camera);
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo_library),
                title: const Text('本地相册'),
                onTap: () {
                  Navigator.pop(context);
                  _pickImage(ImageSource.gallery);
                },
              ),
              ListTile(
                leading: const Icon(Icons.cancel),
                title: const Text('取消'),
                onTap: () => Navigator.pop(context),
              ),
            ],
          ),
        );
      },
    );
  }

  Future<void> _pickImage(ImageSource source) async {
    try {
      final XFile? image = await _imagePicker.pickImage(
        source: source,
        imageQuality: 50,
        maxWidth: 800,
        maxHeight: 800,
      );

      if (image != null) {
        // 显示加载提示
        _showLoadingDialog('正在保存');

        await _uploadImage(image);

        // 关闭加载提示
        if (mounted) Navigator.of(context).pop();
      }
    } catch (e) {
      if (mounted) Navigator.of(context).pop();
      _showMessage('图片选择失败: $e');
    }
  }

  Future<void> _uploadImage(XFile image) async {
    try {
      final bytes = await image.readAsBytes();
      final base64String = base64Encode(bytes);
      final uploadFileUrl = await SJXApi.instance().uploadImage(base64String);

      // 更新用户头像
      await _updateUserAvatar(uploadFileUrl);

      viewModel.setAvatarUrl(uploadFileUrl);

      _showMessage('头像更新成功');
    } catch (e) {
      _showMessage('头像上传失败: $e');
    }
  }

  Future<void> _updateUserAvatar(String imageUrl) async {
    await SJXApi.instance().updateUserInfo({"avatar": imageUrl});
    // 更新本地用户信息
    final user = await SpUtils.getUserData();
    if (user != null) {
      final updatedUser = user.copyWith(avatar: imageUrl);
      SpUtils.saveUserData(updatedUser);
    }

  }

  void _editUserName() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PersonEditPage(
          initialName: viewModel.userName,
          onSave: (newName) {
            viewModel.setUserName(newName);
          },
        ),
      ),
    );
  }

  void _showLoadingDialog(String message) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const CircularProgressIndicator(),
              const SizedBox(height: 16),
              Text(message),
            ],
          ),
        );
      },
    );
  }

  void _showMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 2),
      ),
    );
  }
}